package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapters.XJJLListAdapter;
import mytools.MyBaseActivity;
import objects.HE_XJJL_Detail;
import objects.HE_XJYS;
import objects.InPatient;
import service.WebService;

public class HeathEducateRecordsActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout herd_swipteLayout;
    private ExpandableListView herd_expandableLV;
    private String mHERecordResult;
    private static ProgressDialog progressDialog;
    private List<HE_XJJL_Detail> mHERdList;
    private XJJLListAdapter mXJJLAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heath_educate_records);
        onBindUI();
        setNeedsMenuKey();
        herd_swipteLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        herd_swipteLayout.setOnRefreshListener(this);
        mXJJLAdapter = new XJJLListAdapter(this);
        herd_expandableLV.setAdapter(mXJJLAdapter);
        herd_expandableLV.setOnItemLongClickListener(myItemLongClickListener);
    }

    private void onBindUI() {
        herd_swipteLayout = findViewById(R.id.he_records_swiptelv);
        herd_expandableLV = findViewById(R.id.he_records_expandablelv);
    }

    @Override
    protected void onResume() {
        super.onResume();
        doFlushData(true);
    }

    @Override
    public void onRefresh() {
        doFlushData(false);
    }

    //显示虚拟菜单按钮
    private void setNeedsMenuKey() {
        try {
            Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class);
            setNeedsMenuKey.setAccessible(true);
            int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null);
            setNeedsMenuKey.invoke(getWindow(), value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取健康宣教记录
     */
    private class MyGetHERecordsTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService getHEWebService = new WebService(HeathEducateRecordsActivity.this);
            getHEWebService.setMETHOD_NAME("getXJJL");
            String result;
            getHEWebService.setPARMS(params);
            result = getHEWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取健康宣教记录为空！";
            } else {
                if (!result.equals(mHERecordResult)) {
                    mHERecordResult = result;
                    Gson gson = new Gson();
                    mHERdList = gson.fromJson(mHERecordResult, new TypeToken<List<HE_XJJL_Detail>>() {
                    }.getType());
                    if (mHERdList != null && mHERdList.size() > 0) {
                        return null;
                    } else {
                        return "获取健康宣教表记录失败!";
                    }
                } else {
                    return "健康宣教记录数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String message) {
            super.onPostExecute(message);
            if (herd_swipteLayout.isNestedScrollingEnabled()) {
                herd_swipteLayout.setRefreshing(false);
            }
            cancelProgressBar();
            if (message != null) {
                Toast.makeText(HeathEducateRecordsActivity.this, message, Toast.LENGTH_SHORT).show();
            } else {
                Map<HE_XJYS, List<HE_XJJL_Detail>> dataSets = new HashMap<>();
                List<HE_XJYS> xjysList = new ArrayList<>(dataSets.keySet());
                for (HE_XJJL_Detail heXjjlDetail : mHERdList) { //task获取到的数据循环
                    int position = 0;
                    boolean[] isContained = {false, false};
                    for (HE_XJYS heXjys : xjysList) {
                        if (heXjjlDetail.getYSBS().equals(heXjys.getYSBS())) {
                            isContained[0] = true;
                            List<HE_XJJL_Detail> xjjlList = dataSets.get(heXjys);
                            for (HE_XJJL_Detail xjxm : xjjlList) {
                                if (heXjjlDetail.getJLXH().equals(xjxm.getJLXH())) {
                                    isContained[1] = true;
                                    break;
                                }
                            }
                            break;
                        }
                        position++;
                    }
                    if (!isContained[0]) { //宣教样式不存在
                        HE_XJYS nXJYS = new HE_XJYS(heXjjlDetail.getYSBS(), heXjjlDetail.getYSMC());
                        xjysList.add(nXJYS);
                        List<HE_XJJL_Detail> xjxmList = new ArrayList<>();
                        xjxmList.add(heXjjlDetail);
                        dataSets.put(nXJYS, xjxmList);
                    } else if (!isContained[1]) { //宣教项目明细不存在
                        dataSets.get(xjysList.get(position)).add(heXjjlDetail);
                    }
                }
                mXJJLAdapter.setDataSets(dataSets);
                mXJJLAdapter.notifyDataSetChanged();
                for (int i = 0; i < mXJJLAdapter.getGroupCount(); i++) { //全部展开
                    herd_expandableLV.expandGroup(i);
                }
            }
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    private void doFlushData(boolean isShowProgressBar) {
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            String ZYH = inPatient.getZYH();
            if (ZYH != null) {
                if (isShowProgressBar) {
                    showProgressBar(this);
                }
                String[] parms = {ZYH};
                new MyGetHERecordsTask().execute(parms);
            }
        }
    }

    private AdapterView.OnItemLongClickListener myItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            final long packedPosition = herd_expandableLV.getExpandableListPosition(position);
            final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
            final int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);
            if (childPosition != -1) {//长按的是group的时候，childPosition = -1
                AlertDialog.Builder builder = new AlertDialog.Builder(HeathEducateRecordsActivity.this);
                builder.setTitle("警告");
                builder.setMessage("您正在试图作废该条记录，确定要执行吗？");
                builder.setPositiveButton("确定", (dialog, which) -> {
                    HE_XJJL_Detail heXjjlDetail = (HE_XJJL_Detail) mXJJLAdapter.getChild(groupPosition, childPosition);
                    new MyCancelTask().execute(heXjjlDetail.getJLXH());
                    doFlushData(true);
//                        Toast.makeText(HeathEducateRecordsActivity.this, "JLXH is " + heXjjlDetail.getJLXH(), Toast.LENGTH_SHORT).show();
                });
                builder.setNegativeButton("取消", null);
                builder.show();
            }
            return true;
        }
    };


    //作废宣教记录
    private class MyCancelTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... params) {
            WebService cancelHEWebService = new WebService(HeathEducateRecordsActivity.this);
            cancelHEWebService.setMETHOD_NAME("cancelXJJL");
            String result;
            cancelHEWebService.setPARMS(params);
            result = cancelHEWebService.getServerData();
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            String showInfo = Integer.valueOf(s) > 0 ? "作废成功！" : "作废失败！";
            Toast.makeText(HeathEducateRecordsActivity.this, showInfo, Toast.LENGTH_SHORT).show();
        }
    }

}
